package com.example.myapplication.fragment;

import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.airbnb.lottie.utils.Utils;
import com.example.myapplication.R;
import com.example.myapplication.model.Word;
import com.example.myapplication.service.MusicController;
import com.example.myapplication.service.PlayListener;
import com.example.myapplication.utils.Preference;
import com.example.myapplication.utils.SQLiteHelper;
import com.example.myapplication.utils.TTSHelper;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

public class WordFragment extends Fragment implements View.OnClickListener {

    private View mRootView;
    private EditText idxStart;
    private EditText idxEnd;

    private SeekBar mSeekBar;
    private boolean isPlaying = false;
    private ImageView btnPlay;

    private Button mBtnQuery;
    private List<Word> wordList = new ArrayList<>();
    private int currIndex = 0; //当前显示的单词

    private ImageButton mBtnLeft;
    private ImageButton mBtnRight;
    private TextView mTransTv;
    private TextView mWordTv,mSpeedTv;
    private int repeat = 0;
    private int repeatCount = 0;
    private Button btnDelayAdd;
    private Button btnDelayMinus;
    private Button btnSpeedAdd;
    private Button btnSpeedMinus;
    private int delay = 400;
    private TextView delayTv;
    private TextView labelTv;

    private boolean showTranslation = true;
    private float speed = 1.0f;


    @Override
    public void onClick(View view) {
        if(view.getId() == R.id.btn_query) {
            mWordTv.setText("");
            mTransTv.setText("");
            currIndex = 0;

            String DB = Preference.getInstance(getContext()).getWordDb();
            String start = idxStart.getText().toString();
            String end = idxEnd.getText().toString();
            wordList = SQLiteHelper.getInstance(getContext()).query(DB, start, end);


            labelTv.setText( "0/0");

            if(wordList.size() >= 1) {
                mSeekBar.setMax(wordList.size());
                mSeekBar.setProgress(currIndex);
                updateWordView(0);

                labelTv.setText( "1/" + wordList.size());
            }
        } else if(view.getId() == R.id.btn_left) {
            updateWordView(-1);
        } else if(view.getId() == R.id.btn_right) {
            updateWordView(1);
        } else if(view.getId() == R.id.word) {
            setPlaying(false);
            TTSHelper.getInstance(getActivity()).speak(wordList.get(currIndex).en);
        } else if(view.getId() == R.id.btn_play) {
            setPlaying(!isPlaying);
            if(isPlaying) {
                TTSHelper.getInstance(getActivity()).speak("");
            }
        } else if(view.getId() == R.id.delay_add) {
            setDelay(200);
        } else if(view.getId() == R.id.delay_minus) {
            setDelay(-200);
        } else if(view.getId() == R.id.translation) {
            showTranslation = !showTranslation;
            updateWordView(0);
        } else if(view.getId() == R.id.speed_add) {
            setTTSSpeed(0.1f);
        } else if(view.getId() == R.id.speed_minus) {
            setTTSSpeed(-0.1f);
        }
    }

    private void setTTSSpeed(float what) {
        speed += what;
        speed = Math.max(0.1f,speed);
        speed = Math.min(2.0f,speed);
        TTSHelper.getInstance(getActivity()).setSpeed(speed);
        mSpeedTv.setText( String.format("%.1f"  ,  speed)  );
    }


    private void setDelay(int offset) {
        delay += offset;
        delay = Math.max(200, delay);
        delay = Math.min(8000, delay);
        delayTv.setText(delay+"");
    }

    private void setPlaying(boolean what) {
        isPlaying = what;
        btnPlay.setBackground(
                getResources().getDrawable(
                        isPlaying ? R.drawable.ic_pause : R.drawable.ic_play )
        );
    }


    private void updateWordView(int offset) {
        if(currIndex + offset >= 0 && currIndex + offset < wordList.size()) {
            currIndex += offset;
            mSeekBar.setProgress(currIndex);
            mWordTv.setText( wordList.get(currIndex).en );
            //TODO 设置翻译视图
            if(showTranslation) {
                mTransTv.setText(wordList.get(currIndex).getTranslation());
            } else {
                mTransTv.setText("");
            }
            labelTv.setText(  (currIndex + 1) + "/" + wordList.size() );
        }
    }

    private String wordListToString() {
        String txt = "";
        for (Word w: wordList) {
            txt += w.en;
            txt += ";";
        }
        return txt;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTTSEvent(Object obj) {
        if(isPlaying) {
            updateWordView(0);

            btnPlay.postDelayed(new Runnable() {
                @Override
                public void run() {
                    TTSHelper.getInstance(getActivity()).speak(wordList.get(currIndex).en);
                    if(++repeatCount >= repeat) {
                        currIndex++;
                        repeatCount = 0;
                    }
                }
            }, delay);



        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {

        TTSHelper.getInstance(getActivity());

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        mRootView = inflater.inflate(R.layout.fragment_word, container, false);

        RadioGroup btnWordDB = mRootView.findViewById(R.id.btn_word_db);

        idxStart = mRootView.findViewById(R.id.idx_start);
        idxEnd = mRootView.findViewById(R.id.idx_end);
        RadioButton btnNormal = mRootView.findViewById(R.id.normal);
        RadioButton btnReverse = mRootView.findViewById(R.id.reverse);
        RadioButton btnRandom = mRootView.findViewById(R.id.random);

        mBtnLeft = mRootView.findViewById(R.id.btn_left);
        mBtnRight = mRootView.findViewById(R.id.btn_right);
        mTransTv = mRootView.findViewById(R.id.translation);
        mWordTv = mRootView.findViewById(R.id.word);
        mSpeedTv = mRootView.findViewById(R.id.speed);

        mBtnQuery = mRootView.findViewById(R.id.btn_query);

        mSeekBar = mRootView.findViewById(R.id.progress_bar);
        btnPlay = mRootView.findViewById(R.id.btn_play);
        btnDelayAdd = mRootView.findViewById(R.id.delay_add);
        btnDelayMinus = mRootView.findViewById(R.id.delay_minus);
        delayTv = mRootView.findViewById(R.id.delay);

        btnSpeedAdd = mRootView.findViewById(R.id.speed_add);
        btnSpeedMinus = mRootView.findViewById(R.id.speed_minus);
        labelTv = mRootView.findViewById(R.id.label);

        Spinner repeatSP = mRootView.findViewById(R.id.repeat);

        repeatSP.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                String str = getResources().getStringArray(R.array.repeat_count)[i];
                repeat = Integer.parseInt(str);
                repeatCount = repeat;
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        btnPlay.setOnClickListener(this);
        mBtnQuery.setOnClickListener(this);
        mBtnLeft.setOnClickListener(this);
        mBtnRight.setOnClickListener(this);
        mWordTv.setOnClickListener(this);
        btnDelayAdd.setOnClickListener(this);
        btnDelayMinus.setOnClickListener(this);
        mTransTv.setOnClickListener(this);

        btnSpeedAdd.setOnClickListener(this);
        btnSpeedMinus.setOnClickListener(this);



        mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean b) {
                currIndex = progress;
                updateWordView( 0 );
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        RadioGroup btnWordOrder = mRootView.findViewById(R.id.btn_word_order);

        btnWordOrder.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.normal:
                        Preference.getInstance(getContext()).setOrder(0);
                        break;
                    case R.id.reverse:
                        Preference.getInstance(getContext()).setOrder(1);
                        break;
                    case R.id.random:
                        Preference.getInstance(getContext()).setOrder(2);
                        break;
                }
            }
        });

        int order = Preference.getInstance(getContext()).getOrder();

        switch (order) {
            case 0:
                btnNormal.setChecked(true);
                break;
            case 1:
                btnReverse.setChecked(true);
                break;
            case 2:
                btnRandom.setChecked(true);
                break;
        }


        idxStart.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                String str = idxStart.getText().toString();
                int idx = Integer.parseInt(str);
                Preference.getInstance(getContext()).setStartIdx(idx);
            }
        });

        idxEnd.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                String str = idxEnd.getText().toString();
                int idx = Integer.parseInt(str);
                Preference.getInstance(getContext()).setEndIdx(idx);
            }
        });


        int startIdx = Preference.getInstance(getContext()).getStartIdx();
        idxStart.setText( startIdx + ""  );
        int endIdx = Preference.getInstance(getContext()).getEndIdx();
        idxEnd.setText( endIdx + ""  );

        int idx = 0;
        String wordDB= Preference.getInstance(getContext()).getWordDb();

        switch (wordDB) {
            case "CET6":
                idx = R.id.cet6;
                break;
            case "TOEFL":
                idx = R.id.toefl;
                break;
            case "Postgraduate":
                idx = R.id.postgraduate;
                break;
        }

        btnWordDB.check(idx);

        btnWordDB.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.cet6:
                        //持久化单词数据库 CET6
                        Preference.getInstance(getContext()).setWordDB("CET6");
                        break;
                    case R.id.toefl:
                        //持久化单词数据库 toefl
                        Preference.getInstance(getContext()).setWordDB("TOEFL");
                        break;
                    case R.id.postgraduate:
                        //持久化单词数据库 ielts
                        Preference.getInstance(getContext()).setWordDB("Postgraduate");
                        break;
                }
            }
        });

        return mRootView;
    }




}
